import React, { useEffect, useRef } from 'react';
import { Graph, Extensions } from '@antv/g6';
import { generateRows } from './data';

interface Props {
  width?: number;
  height?: number;
}

export default function G6Graph({ width = 1200, height = 600 }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    // 1. 生成数据
    const rows = generateRows(100);
    const nodes: any[] = [];
    const edges: any[] = [];
    const ROW_H = 120;
    const NODE_W = 160;

    rows.forEach((row, r) => {
      row.devices.forEach((dev, i) => {
        nodes.push({
          id: dev.id,
          data: { ...dev },
          x: i * NODE_W,
          y: r * ROW_H,
        });
        if (i > 0) {
          edges.push({ source: row.devices[i - 1].id, target: dev.id });
        }
      });
    });

    // 2. 注册扩展（必须放在 new Graph 之前）
    Extensions.register(
      'preset-layout',
      Extensions.Builtin.Layouts['preset-layout']
    );
    Extensions.register('drag-node', Extensions.Builtin.Behaviors['drag-node']);
    Extensions.register('drag-canvas', Extensions.Builtin.Behaviors['drag-canvas']);
    Extensions.register('zoom-canvas', Extensions.Builtin.Behaviors['zoom-canvas']);
    Extensions.register('minimap', Extensions.Builtin.Plugins['minimap']);

    // 3. 实例化图
    const graph = new Graph({
      container: containerRef.current,
      width,
      height,
      data: { nodes, edges },
      node: {
        type: 'rect',
        style: {
          width: 60,
          height: 30,
          radius: 4,
          fill: (d: any) =>
            d.data.type === 'router'
              ? '#ff5722'
              : d.data.type === 'switch'
              ? '#2196f3'
              : '#4caf50',
          labelText: (d: any) => d.data.name,
          labelFill: '#fff',
          labelFontSize: 12,
        },
      },
      edge: { type: 'line', style: { stroke: '#aaa', lineWidth: 1 } },
      layout: { type: 'preset-layout' },
      behaviors: ['drag-node', 'drag-canvas', 'zoom-canvas'],
      plugins: [{ type: 'minimap', size: [200, 120] }],
    });

    // 4. 渲染
    graph.render().then(() => graph.fitView());

    return () => graph.destroy();
  }, [width, height]);

  return <div ref={containerRef} style={{ width, height }} />;
}